import sys
from PySide6.QtCore import QCoreApplication, QMetaObject, QSize, Qt
from PySide6.QtWidgets import (QApplication, QComboBox, QHeaderView, QSizePolicy,
                               QTableWidget, QTableWidgetItem, QVBoxLayout, QHBoxLayout,
                               QCheckBox, QWidget, QPushButton, QLabel)
from qfluentwidgets import TableWidget, PushButton


class DataSelectTable(QWidget):
    def __init__(self):
        super().__init__()
        self.totalPages = 0
        self.totalItems = 0
        self.pPageLabel = None
        self.pNextButton = None
        self.pPrevButton = None
        self.paginatorLayout = None
        self.dataSelectTable = None
        self.itemSelectComboBox = None
        self.mainLayout = None
        self.currentPage = 1
        self.itemsPerPage = 10
        self.checkboxStates = {}  # 用于保存复选框状态的字典
        self.setupUi(self)

    def setupUi(self, Form):
        self.adjustSize()
        self.setContentsMargins(0, 0, 0, 0)
        # 创建主布局
        self.mainLayout = QVBoxLayout(Form)
        self.setLayout(self.mainLayout)
        self.mainLayout.setSpacing(10)
        self.mainLayout.setContentsMargins(0, 0, 0, 0)
        self.mainLayout.setObjectName(u"mainLayout")

        self.itemSelectComboBox = QComboBox(Form)
        # itemList = []
        # self.itemSelectComboBox.addItem()
        self.itemSelectComboBox.setStyleSheet("QComboBox { padding-left: 40px; padding-right: 40px; }")
        self.itemSelectComboBox.setPlaceholderText("-- 请选择项目 --")
        self.itemSelectComboBox.setCurrentIndex(-1)
        self.itemSelectComboBox.setObjectName(u"comboBox")
        sizePolicy = QSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
        self.itemSelectComboBox.setSizePolicy(sizePolicy)
        self.itemSelectComboBox.setMinimumSize(QSize(200, 35))
        self.mainLayout.addWidget(self.itemSelectComboBox)

        # 创建表格布局
        self.dataSelectTable = TableWidget(Form)
        self.dataSelectTable.setObjectName(u"itemTable")
        self.dataSelectTable.setColumnCount(3)
        self.dataSelectTable.setRowCount(10)

        # 设置表格行高(高度不太够)
        # 通过循环设置每一行的高度
        for row in range(self.dataSelectTable.rowCount()):
            self.dataSelectTable.setRowHeight(row, 35)  # 设置所有行的高度为35
        self.dataSelectTable.setRowCount(self.itemsPerPage)
        tableSizePolicy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        self.dataSelectTable.setSizePolicy(tableSizePolicy)
        self.dataSelectTable.setHorizontalHeaderLabels(["矿井序号", "具体名称", "确认导入"])
        self.dataSelectTable.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.dataSelectTable.verticalHeader().setVisible(False)  # 行号
        self.mainLayout.addWidget(self.dataSelectTable)

        # 添加分页器
        self.paginatorLayout = QHBoxLayout()
        self.paginatorLayout.setSpacing(10)
        self.paginatorLayout.setContentsMargins(120, 0, 120, 0)  # 居中显示，增大左右边距
        self.pPrevButton = PushButton()
        self.pPrevButton.setText("上一页")
        self.pPrevButton.setObjectName("pPrevButton")
        self.pPrevButton.setFixedSize(150, 30)
        self.pNextButton = PushButton()
        self.pNextButton.setText("下一页")
        self.pNextButton.setObjectName("pNextButton")
        self.pNextButton.setFixedSize(150, 30)
        self.pPageLabel = QLabel()
        self.paginatorLayout.addWidget(self.pPrevButton)
        self.paginatorLayout.addWidget(self.pPageLabel)
        self.paginatorLayout.addWidget(self.pNextButton)
        self.mainLayout.addLayout(self.paginatorLayout)

        self.pPrevButton.clicked.connect(self.prevPage)
        self.pNextButton.clicked.connect(self.nextPage)

        self.populateTable()

        QMetaObject.connectSlotsByName(Form)

    def populateTable(self):

        # 保存当前页复选框状态
        self.saveCheckboxStates()

        # 清空表格内容
        self.dataSelectTable.clearContents()

        # 假设有50行数据
        self.totalItems = 55
        self.totalPages = (self.totalItems + self.itemsPerPage - 1) // self.itemsPerPage

        # 更新分页器显示
        self.updatePageLabel()
        startRow = (self.currentPage - 1) * self.itemsPerPage
        endRow = min(startRow + self.itemsPerPage, self.totalItems)

        for row in range(startRow, endRow):
            tableRow = row - startRow
            for col in range(2):
                item = QTableWidgetItem(f"Item {row + 1}, {col + 1}")
                item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)  # 居中对齐
                self.dataSelectTable.setItem(tableRow, col, item)

            # 创建复选框并将其居中
            checkBoxWidget = QWidget()
            checkBoxLayout = QHBoxLayout(checkBoxWidget)
            checkBoxLayout.setAlignment(Qt.AlignmentFlag.AlignCenter)  # 设置布局居中
            checkBoxLayout.setContentsMargins(0, 0, 0, 0)  # 去除边距
            checkBox = QCheckBox()

            # 恢复复选框状态
            checkBox.setChecked(self.checkboxStates.get(row, False))

            checkBoxLayout.addWidget(checkBox)
            self.dataSelectTable.setCellWidget(tableRow, 2, checkBoxWidget)

        # 自动调整表格高度以适应行数
        self.dataSelectTable.setFixedHeight(
            self.dataSelectTable.verticalHeader().sectionSize(
                0) * self.itemsPerPage + self.dataSelectTable.horizontalHeader().height() + 5)
        self.resize(800, self.dataSelectTable.verticalHeader().sectionSize(
            0) * self.itemsPerPage + self.dataSelectTable.horizontalHeader().height() + 50)
        self.updateButtons()

    def saveCheckboxStates(self):
        """保存当前页的复选框状态"""
        startRow = (self.currentPage - 1) * self.itemsPerPage
        for row in range(self.dataSelectTable.rowCount()):
            checkBoxWidget = self.dataSelectTable.cellWidget(row, 2)
            if checkBoxWidget:
                checkBox = checkBoxWidget.findChild(QCheckBox)
                if checkBox:
                    self.checkboxStates[startRow + row] = checkBox.isChecked()

    def prevPage(self):
        if self.currentPage > 1:
            self.currentPage -= 1
            self.populateTable()

    def nextPage(self):
        if self.currentPage < self.totalPages:
            self.currentPage += 1
            self.populateTable()

    def updatePageLabel(self):
        self.pPageLabel.setText(f"第 {self.currentPage} 页，共 {self.totalPages} 页")
        self.pPageLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)

    def updateButtons(self):
        self.pPrevButton.setEnabled(self.currentPage > 1)
        self.pNextButton.setEnabled(self.currentPage < self.totalPages)

    def selectAll(self):
        """全选表格中的复选框"""
        for row in range(self.dataSelectTable.rowCount()):
            checkBoxWidget = self.dataSelectTable.cellWidget(row, 2)
            if checkBoxWidget:
                checkBox = checkBoxWidget.findChild(QCheckBox)
                if checkBox:
                    checkBox.setChecked(True)
                    self.checkboxStates[(self.currentPage - 1) * self.itemsPerPage + row] = True

    def deselectAll(self):
        """取消选择表格中的所有复选框"""
        for row in range(self.dataSelectTable.rowCount()):
            checkBoxWidget = self.dataSelectTable.cellWidget(row, 2)
            if checkBoxWidget:
                checkBox = checkBoxWidget.findChild(QCheckBox)
                if checkBox:
                    checkBox.setChecked(False)
                    self.checkboxStates[(self.currentPage - 1) * self.itemsPerPage + row] = False


if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainForm = DataSelectTable()
    mainForm.show()
    sys.exit(app.exec())
